package org.fireflow2.designer.eclipse.parts.basic;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;

import org.eclipse.draw2d.Animation;
import org.eclipse.draw2d.ConnectionLayer;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.ShortestPathConnectionRouter;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.LayerConstants;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editparts.AbstractGraphicalEditPart;
import org.eclipse.swt.SWT;
import org.fireflow2.designer.eclipse.figures.SubflowFigure;
import org.fireflow2.designer.eclipse.modelwrapper.SubProcessWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.Wrapper;
import org.fireflow2.designer.eclipse.policies.CommonEmptyXYLayoutEditPolicy;

public class BasicSubProcessPart extends AbstractGraphicalEditPart
		implements PropertyChangeListener {

	@Override
	protected IFigure createFigure() {
		// TODO Auto-generated method stub
		// Figure theFigure = new FreeformLayer();
//		Figure theFigure = new ScalableFreeformLayeredPane();
//		theFigure.setLayoutManager(new FreeformLayout());
		 Figure theFigure = new SubflowFigure();

		return theFigure;

	}

	@Override
	protected void createEditPolicies() {
		// TODO Auto-generated method stub
		installEditPolicy(EditPolicy.LAYOUT_ROLE,
				new CommonEmptyXYLayoutEditPolicy());

	}
	public Command getCommand(Request request) {
		System.out.println("Inside BasicSubfowPart.getCommand()::"+request.getType()+"; request is "+request);
		return super.getCommand(request);
	}
	protected void refreshVisuals() {
		super.refreshVisuals();

		ConnectionLayer connectionLayer = (ConnectionLayer) getLayer(LayerConstants.CONNECTION_LAYER);
		connectionLayer.setConnectionRouter(new ShortestPathConnectionRouter(
				figure));
		if ((getViewer().getControl().getStyle() & SWT.MIRRORED) == 0)
			connectionLayer.setAntialias(SWT.ON);
		Animation.run(400);
	}

	@Override
	protected List getModelChildren() {

		SubProcessWrapper workflowProcessWrapper = (SubProcessWrapper) this
				.getModel();

		List children = workflowProcessWrapper.getAllNodes4GraphEditor();
		return children;
	}

	public void activate() {
		super.activate();
		((SubProcessWrapper) getModel()).addPropertyChangeListener(this);
	}

	public void deactivate() {
		super.deactivate();
		((SubProcessWrapper) getModel()).removePropertyChangeListener(this);
	}

	public void propertyChange(PropertyChangeEvent evt) {
		// this.refreshVisuals();
		String prop = evt.getPropertyName();
//		if (SubProcessWrapper.NODE.equals(prop)){
//			refreshChildren();
//		}else if (SubProcessWrapper.TRANSITION.equals(prop)){
//			System.out.println("========Add a transition");
//		}
		if (!Wrapper.DIRTY.equals(prop)){
			refresh();
		}
		
	}
}
